package cn._51doit.flink.day02;

import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.source.SourceFunction;
import org.apache.kafka.common.protocol.types.Field;

import java.util.Arrays;
import java.util.List;
import java.util.UUID;

/**
 * Source 如果在run方法中，执行的逻辑，有while循环, 不停的产生数据，所以这样的Source是无限的数据源
 *
 * 如果实现的是SourceFunction接口，那么该Source 一定是一个非并行的Source，即并行度为1
 */
public class CustomSource2 {

    public static void main(String[] args) throws Exception {

        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        //可以认为设置执行环境的并行度
        //env.setParallelism(6);
        //System.out.println(env.getParallelism());

        DataStreamSource<String> lines = env.addSource(new MySource2());

        lines.print();

        env.execute();


    }

    private static class MySource2 implements SourceFunction<String> {

        /**
         * Source负责读取数据，然后使用SourceContext将数据输出给后面的算子使用
         * @param ctx
         * @throws Exception
         */
        @Override
        public void run(SourceContext<String> ctx) throws Exception {
            System.out.println("run method invoked !!!");
            //在run定义可以while循环
            while (true) {
                String str = UUID.randomUUID().toString();
                ctx.collect(str);
                Thread.sleep(1000);
            }
        }

        @Override
        public void cancel() {
            System.out.println("cancel method invoked @@@");
        }
    }
}
